import router from './router'
import store from './store'
import {Message} from 'element-ui'
import {getToken} from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

function hasPermission(roles, permissionRoles) {
  if (!permissionRoles) {
    return true
  }
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

// 白名单集合，白名单页面路由在这里添加
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({path: '/'})
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        store.dispatch("GetUserInfo").then(res => {
          const role = res.data.data.role
          let roles
          if (role === '1') {
            roles = ['common']
          } else if (role === '0' ) {
            roles = ['admin']
          }
          store.dispatch('GenerateRoutes', {roles}).then(() => {
            router.addRoutes(store.getters.addRouters)
            next({...to, replace: true})
          })
        }).catch((err) => {
          store.dispatch('FrontLogout').then(() => {
            Message.error(err || '验证错误，请重新登录！')
            next({path: '/'})
          })
        })
      } else {
        if (hasPermission(store.getters.roles, to.meta.roles)) {
          next()
        }  else {
          next({path: '/401', replace:true, query: {noGoBack: true}})
        }
      }
    }
  } else {
     if (whiteList.indexOf(to.path) !== -1) {
       next()
     } else {
       next(`/login?redirect=${to.path}`)
       NProgress.done()
     }
  }
})

router.afterEach(() => {
  NProgress.done()
})

